package com.mybatis.controller.sys.websocket;

import java.io.IOException;
import java.io.InputStream;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;

@ServerEndpoint("/webLog")
public class LogWebSocketHandle {

	private static final Logger log = Logger.getLogger(LogWebSocketHandle.class);
	
	private Process process;
	private InputStream inputStream;
	
	/**
	 * 新的WebSocket请求开启
	 */
	@OnOpen
	public void onOpen(Session session) {
		try {
			log.info("osName:"+System.getProperties().getProperty("os.name"));
			// 执行tail -f命令
			process = Runtime.getRuntime().exec("tail -f /usr/local/tomcat/logs/catalina.out");
			inputStream = process.getInputStream();
			
			// 一定要启动新的线程，防止InputStream阻塞处理WebSocket的线程
			TailLogThread thread = new TailLogThread(inputStream, session);
			log.info("------WebSocket链接开始------");
			thread.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * WebSocket请求关闭
	 */
	@OnClose
	public void onClose() {
		try {
			if(inputStream != null) inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(process != null) process.destroy();
		log.info("------WebSocket链接结束------");
	}
	
	@OnError
	public void onError(Throwable thr) {
		log.info("------WebSocket链接错误------");
		thr.printStackTrace();
	}
}